package com.brothers.thisGame.basic;

import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import org.slf4j.LoggerFactory;
import com.brothers.thisGame.Game;
import com.brothers.thisGame.Player;

public class BasicGame extends Observable implements Game {
	final static org.slf4j.Logger LOGGER = LoggerFactory
			.getLogger(BasicGame.class);
	Map<Player, Integer> bettingTable = new HashMap<Player, Integer>();
	Player maker;
	float odds = 1;
	int totalScoreLimit = 999999999;

	public Map<Player, Integer> getBettingTable() {
		return bettingTable;
	}

	public Player getMaker() {
		return maker;
	}

	public void setMaker(Player maker) {
		this.maker = maker;
	}

	public float getOdds() {
		return odds;
	}

	public void setOdds(float odds) {
		this.odds = odds;
	}

	public int getTotalScoreLimit() {
		return totalScoreLimit;
	}

	public void setTotalScoreLimit(int totalScoreLimit) {
		this.totalScoreLimit = totalScoreLimit;
	}

	@Override
	public boolean isWinner(Player player) {
		// TODO 此处算法待实现
		return false;
	}

	@Override
	public boolean isMaker(Player player) {
		return player.equals(maker);
	}

	@Override
	public void deal() {
		// 判定每位玩家的胜负并按规则支付筹码给胜出的玩家
		for (Player player : getBettingTable().keySet()) {
			if (isWinner(player)) {
				pay(player);
			} else {
				eat(player);
			}
		}
	}

	@Override
	public void pay(Player player) {
		// 获得玩家下注额
		int playersBet = bettingTable.get(player) == null ? 0 : bettingTable
				.get(player).intValue();

		int playersIncome = (int) (playersBet * odds); // 玩家收益
		player.gain(playersBet + playersIncome);

		maker.lose(playersIncome);

		LOGGER.debug(String.format("玩家%s赢得了%d个筹码，现有%d个筹码。", player.getNick(),
				playersIncome - playersBet, player.getRemaining()));

		LOGGER.debug(String.format("庄家%s输掉了%d个筹码，现有%d个筹码。", maker.getNick(),
				playersIncome, maker.getRemaining()));
	}

	@Override
	public void eat(Player player) {
		// 获取该玩家在本局的投注额
		int playersBet = bettingTable.get(player) == null ? 0 : bettingTable
				.get(player).intValue();

		// 庄家赢得玩家押注的筹码
		maker.gain(playersBet);

		LOGGER.debug(String.format("玩家%s输掉了%d个筹码，现有%d个可用筹码。", player.getNick(),
				playersBet, player.getRemaining()));

		LOGGER.debug(String.format("庄家%s赢得了%d个筹码，现有%d个可用筹码。", maker.getNick(),
				playersBet, maker.getRemaining()));

	}

	@Override
	public void earn() {
		// TODO Auto-generated method stub
	}

}
